using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Web.Ajax.Controls
{
	[ToolboxData("<MenuItem></MenuItem>")]
	public class PopupMenuItem : WebControl
	{
		#region Type
		/// <summary>
		/// Provides render options for the menuitem.
		/// </summary>
		public enum ItemType
		{
			Normal,
			Separator,
			Heading
		}
		/// <summary>
		/// The Type of this menu item.
		/// </summary>
		public ItemType Type = ItemType.Normal; 
		#endregion

		#region Text
		/// <summary>
		/// The Text to display in this menu item.
		/// </summary>
		public string Text = "Menu Item";
		#endregion

		#region Url
		/// <summary>
		/// The Url to go to when this menu item is clicked.
		/// </summary>
		public string Url = "";
		#endregion

		#region OnClick
		/// <summary>
		/// The Client side Javascript to Execute when this menu item is clicked.
		/// </summary>
		public string OnClick = "";
		#endregion

		#region Render
		/// <summary>
		/// Renders the Html for the Menu Item control.
		/// </summary>
		/// <param name="writer">The HtmlTextWriter object to render to.</param>
		protected override void Render(HtmlTextWriter writer)
		{
			if(!Visible)
				return;
			StringBuilder html = new StringBuilder();
			string ClickScript = OnClick;
			if (!string.IsNullOrEmpty(Url))
				ClickScript += ";location.href='" + Url + "';";
			string Css = "MenuItem";
			html.Append("<tr #JS #RCSS id=\""+JavascriptId+"\">");
			bool Clickable = true;
			switch (Type)
			{
				case ItemType.Separator:
					html.Append("<td class=\"MenuItemSeparator\" colspan=\"20\"></td>");
					Clickable = false;
					break;
				case ItemType.Heading:
					Css = "MenuItemHeading";
					Clickable = false;
					break;
			}
			if (Type != ItemType.Separator)
			{
				if (string.IsNullOrEmpty(Text))
				{
					html.Append("<td class=\"#CSS\" colspan=\"20\"></td>");
				}
				else
				{
					string[] parts = Text.Split(',');
					for (int i = 0; i < parts.Length; i++)
					{
						html.Append("<td class=\"#CSS\">#TXT</td>");
						html.Replace("#CSS", Css);
						html.Replace("#TXT", parts[i]);
					}
				}
			}
			html.Append("</tr>");
			ClickScript += WebControl.GetJavascriptId(Parent) + ".Hide();";
			if (Clickable)
				html.Replace("#JS", "onclick=\""+ClickScript+"\"");
			else
				html.Replace("#JS", "");
			if (Clickable)
				html.Replace("#RCSS", "class=\"MenuItemRow\"");
			else
				html.Replace("#RCSS", "");
			writer.Write(html.ToString());
		}
		#endregion
	}
}
